package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.microsoft.schemas.office.visio.x2012.main.MasterContentsDocument;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishFlavorsMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.beans.Transient;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Service
public class DishServiceImpl implements DishService {


    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private DishFlavorsMapper dishFlavorsMpper;

    @Autowired
    private SetmealDishMapper setmealDishMapper;

    @Autowired
    private SetmealMapper setmealMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 菜品新增
     * @param dishDTO
     */
    @Override
    public void add(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        dishMapper.add(dish);

        //获取菜品主键id
        Long id = dish.getId();

        //获取口味表口味
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors != null && flavors.size()>0){
            flavors.forEach(dishFlavor -> {
                dishFlavor.setDishId(id);
            });
            dishFlavorsMpper.insert(flavors);
        }

    }

    /**
     * 菜品分页
     * @param pageDTO
     * @return
     */
    @Override
    public PageResult pageQuery(DishPageQueryDTO pageDTO) {
        //设置分页查询的页数和每页数
        PageHelper.startPage(pageDTO.getPage(),pageDTO.getPageSize());
       Page<DishVO> pa= dishMapper.pageQuery(pageDTO);

       //返回的页数和每页数
        PageResult pageResult = new PageResult();
        pageResult.setTotal(pa.getTotal());
        pageResult.setRecords(pa.getResult());
        return pageResult;
    }

    /**
     * 删除菜品
     * @param ids
     */
    @Override
   @Transactional
    public void delete(List<Long> ids) {
        //查询删除菜品中有启售状态，有抛出异常，启售状态不能删除
      int count=  dishMapper.getCountByStatus(ids, StatusConstant.ENABLE);
        if (count > 0) {
           throw  new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
        }
        //判断菜品跟套餐关联，关联不删除
        int count2=dishMapper.getDishAndSetmeal(ids);
        if(count2 > 0){
           throw   new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }

        //除去这两个条件，ids是可以删除，菜品表跟关联的口味表
        dishMapper.deleteDish(ids);
        dishFlavorsMpper.deleteDishFlavor(ids);

    }

    @Override
    public DishVO getByIdWithFlavors(Long id) {
        //查询菜品信息
       Dish dish= dishMapper.getId(id);
       //查询口味信息
      List<DishFlavor> dishFlavors= dishFlavorsMpper.getFlavorsId(id);
      //创建一个传递的封装类
        DishVO dishVO = new DishVO();
        //将菜品信息copy给vo
        BeanUtils.copyProperties(dish,dishVO);
        //将口味信息给vo
        dishVO.setFlavors(dishFlavors);


        return dishVO;
    }

    @Override
    public void update(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        dishMapper.update(dish);


        //删除原有口味
        dishFlavorsMpper.deleteDishFlavor(Arrays.asList(dishDTO.getId()));

        //新增新的口味
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if(flavors != null){
            //不为空，设置菜品id
            for (DishFlavor flavor : flavors) {
                   flavor.setDishId(dish.getId());

                   dishFlavorsMpper.insertFlavors(flavors);
            }
        }
    }

    @Override
    public List<Dish> getByCategoryId(Long categoryId) {
        // 查询categoryId分类下启售状态的菜品
        return dishMapper.getByCategoryId(categoryId, StatusConstant.ENABLE);
    }



    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    @Override
    public List<DishVO> listWithFlavor(Dish dish) {
        //根据分类id查询菜品
        //1.先redis获取缓存数据，确定key的格式dish_category_
        ValueOperations valueOperations = redisTemplate.opsForValue();
        List<DishVO> List = (List<DishVO>) valueOperations.get("dish_category_" + dish.getCategoryId());
        //缓存没有获取到，从数据库查询
        if (List==null){
            List<Dish> dishList = dishMapper.getByCategoryId(dish.getCategoryId(),dish.getStatus());

            List = new ArrayList<>();

            for (Dish d : dishList) {
                DishVO dishVO = new DishVO();
                //查询到的缓存copy到返回结果
                BeanUtils.copyProperties(d,dishVO);

                //根据菜品id查询对应的口味
                List<DishFlavor> flavors = dishFlavorsMpper.getByDishId(d.getId());

                dishVO.setFlavors(flavors);
               List.add(dishVO);
            }
            //将数据存储到redis
            valueOperations.set("dish_category_"+dish.getCategoryId(),List);
        }

        //获取到缓存直接返回
        return List;
    }


}
